package com.jie.other.compose.study04.details

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.blankj.utilcode.util.ToastUtils
import com.jie.other.compose.data.ExploreModel
import com.jie.other.ui.widget.CommonTopAppBar
import kotlinx.coroutines.*

internal const val PARAM_CITY_NAME = "PARAM_CITY_NAME"

fun launchDetails(context : Context, item: ExploreModel) {
    context.startActivity(Intent(context, DetailsActivity::class.java).apply {
        putExtra(PARAM_CITY_NAME, item.city.name)
    })
}

class DetailsActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val cityName = intent.getStringExtra(PARAM_CITY_NAME)?:""
        val viewModel by viewModels<DetailsViewModel>()
        setContent {
            MaterialTheme {
                DetailsPage(
                    cityName = cityName,
                    viewModel = viewModel,
                    backClick = { finish() },
                    onError = {
                        showFailInfo(it)
                    }
                )
            }
        }
    }

    private fun showFailInfo(msg : String) {
        lifecycleScope.launch{
            ToastUtils.showShort(msg)
            delay(2000)
            finish()
        }
    }
}

@SuppressLint("ProduceStateDoesNotAssignValue")
@Composable
fun DetailsPage(
    cityName : String,
    onError : (String) -> Unit = {},
    backClick: () -> Unit = {},
    viewModel: DetailsViewModel,
) {
    Scaffold(
        topBar = {
            CommonTopAppBar(
                title = cityName,
                backClick = backClick
            )
        },
    ) {
        val scope = rememberCoroutineScope()
        val uiState by produceState(UiState(isLoading = true)) {
            scope.launch(Dispatchers.IO) {
                val detailsResult = viewModel.getDetails(cityName)
                value = if (detailsResult.isSuccess) {
                    UiState(cityDetails = detailsResult.getOrNull())
                } else {
                    UiState(isFail = true)
                }
            }
        }
        when {
            uiState.cityDetails != null -> {
                DetailsContent(
                    modifier = Modifier.padding(it),
                    uiState.cityDetails!!
                )
            }
            uiState.isLoading -> {
                Box(modifier = Modifier.fillMaxSize()) {
                    CircularProgressIndicator(
                        color = Color.Red,
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
            }
            uiState.isFail -> {
                onError("加载失败")
            }
        }
    }
}

@Composable
fun DetailsContent(
    modifier: Modifier = Modifier,
    cityDetails: ExploreModel
) {
    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Spacer(modifier = Modifier.height(16.dp))
        Surface(
            modifier = modifier
                .size(120.dp),
            RoundedCornerShape(4.dp)
        ) {
            val imagePainter = rememberAsyncImagePainter(
                ImageRequest.Builder(LocalContext.current)
                    .data(cityDetails.imageUrl).apply(
                        block = fun ImageRequest.Builder.(){
                            crossfade(true)
                        }
                    ).build()
            )
            Image(
                painter = imagePainter,
                contentDescription = cityDetails.city.name,
                contentScale = ContentScale.Crop,
                modifier = Modifier.fillMaxSize(),
            )
        }
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            modifier = Modifier.fillMaxWidth(),
            text = cityDetails.city.nameToDisplay,
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.h4,
        )
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            modifier = Modifier.fillMaxWidth(),
            text = cityDetails.description,
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.body1,
        )
        Spacer(modifier = Modifier.height(16.dp))
    }
}

data class UiState(
    var cityDetails : ExploreModel? = null,
    var isLoading : Boolean = false,
    var isFail : Boolean = false,
)